package com.boyi.center.exception;

import com.boyi.shared.common.Message;
import com.boyi.shared.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 颜培轩
 * @date 2018年08月03日  下午 05:31
 */
@RestControllerAdvice("com.boyi")
public class MyExceptionHandler {
    private static Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);

    @ExceptionHandler(BindException.class)
    public Result handleBindException(BindException e) {
        Map<String, String> data = new HashMap<>();
        for (ObjectError error : e.getAllErrors()) {
            data.put(((FieldError) error).getField(), error.getDefaultMessage());
        }
        Result r = new Result();
        r.setMessage(Message.CHECK_ERROR);
        r.setData(data);
        return r;
    }

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        Result r = new Result();
        r.setMessage(Message.FAILE);
        r.setData(e.getMessage());
        return r;
    }

}
